package cn.test;
import com.iflytek.cloud.speech.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 语音听写类
 * */
public class Recognizer {

    private SpeechRecognizer mIat;
    private static Recognizer recognizer = null;

    private Recognizer(){
        //初始化听写服务
        SpeechUtility.createUtility(SpeechConstant.APPID + "=" + Config.APPID);
        //1.创建SpeechRecognizer对象
        this.mIat = SpeechRecognizer.createRecognizer();
        //2.设置听写参数，详见官网参考手册
        this.mIat.setParameter(SpeechConstant.DOMAIN, "iat");
        this.mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        this.mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
    }

    public static Recognizer getInstance(){
        if(recognizer == null){
            recognizer = new Recognizer();
        }
        return recognizer;
    }

    //听写监听器
    private RecognizerListener mRecoListener = new RecognizerListener() {
        //听写回调接口（返回json格式结果）
        //一般情况下会通过onResults接口多次返回结果，完整的识别内容是多次结果的累加
        //关于解析json的代码可以参考MscDemo中JsonParser类
        //isLast等于true时会话才结束
        @Override
        public void onVolumeChanged(int i) {
        }

        @Override
        public void onBeginOfSpeech() {
        }

        @Override
        public void onEndOfSpeech() {
        }

        @Override
        public void onResult(RecognizerResult recognizerResult, boolean b) {
            JSONObject jsonObject;
            File file;
            try {
                file = new File(Config.TXTFILE);
                jsonObject = new JSONObject(recognizerResult.getResultString());
                int ord = jsonObject.getInt("sn");
                if(ord == 1){
                    Utils.clearFile(file);
                }
                ArrayList<String> results = Utils.parseRecognizerResult(jsonObject);
                Utils.writeRecognizerResult2File(results, file);
                if(b){
                    App.status = "recognizerCompleted";
                    System.out.println("recognizerCompleted");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IOException e){
                e.printStackTrace();
            }
        }

        @Override
        public void onError(SpeechError speechError) {
        }

        @Override
        public void onEvent(int i, int i1, int i2, String s) {
        }
    };


    /*
     * 从语音文件听写
     */
    public void recognizerFromFile(String path2VoiceFile) throws IOException {
        mIat.setParameter(SpeechConstant.AUDIO_SOURCE, "-1");
        mIat.startListening(mRecoListener);
        //听写监听器
        FileInputStream in = new FileInputStream(new File(path2VoiceFile));
        byte[] buffer = new byte[48000];
        while((in.read(buffer))!=-1){
            mIat.writeAudio(buffer, 0, buffer.length);
        }
        mIat.stopListening();
    }

    /*
     * 从麦克风听写
     */
    public void recognizerFromMic(){
        mIat.startListening(mRecoListener);
    }

    public static void main(String[] args) throws IOException {

        Recognizer app = getInstance();
        //从文件读取语音
        app.recognizerFromFile(Config.VOICEFILE);
        //从麦克风识别
        //app.recognizerFromMic();
    }

}
